<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- add begin by zyj 2024/11/07 新增物料编码查询-->
      <el-form-item label="物料编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- add end by zyj 2024/11/07 新增物料编码查询-->
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="SN码" prop="snCode">
        <el-input v-model="queryParams.snCode" placeholder="请输入SN码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产线名称" prop="lineName">
        <el-select v-model="queryParams.lineName" placeholder="请选择产线名称" @change="(val) => lineChange(val, 'queryParams')">
          <el-option v-for="item in lineList" :key="item.lineNo" :label="item.lineName" :value="item.lineName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线ID" prop="lineId" v-show="false">
        <el-input v-model="queryParams.lineId" placeholder="请输入产线ID" clearable disabled />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-select v-model="queryParams.processName" placeholder="请选择工序名称" @change="(val) => processChange(val, 'queryParams')">
          <el-option v-for="item in processList" :key="item.processId" :label="item.processName" :value="item.processName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工序ID" prop="processId" v-show="false">
        <el-input v-model="queryParams.processId" placeholder="请输入工序ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="填报时间">
        <el-date-picker v-model="queryParams.time" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:record:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['workinghours:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['workinghours:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['workinghours:record:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="工单编码" align="center" prop="workorderCode" />
      <el-table-column label="类型" align="center" prop="orderTypeName" />
      <!-- <el-table-column label="类型" align="center" prop="orderType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_type" :value="scope.row.orderType"/>
        </template>
</el-table-column>-->
      <!-- edit begin by zyj 2024/11/07-->
      <!-- <el-table-column label="产品编号" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" /> -->
      <el-table-column label="物料编号" align="center" prop="productCode" />
      <el-table-column label="物料名称" align="center" prop="productName" />
      <!-- edit end by zyj 2024/11/07-->
      <el-table-column label="规格型号" align="center" width="160" prop="productSpc" />
      <el-table-column label="SN码" align="center" prop="snCode">
        <template slot-scope="scope">
          <span>{{ scope.row.snCode || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产线名称" align="center" prop="lineName">
        <template slot-scope="scope">
          <span>{{ scope.row.lineName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工序名称" align="center" prop="processName">
        <template slot-scope="scope">
          <span>{{ scope.row.processName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单数量" align="center" prop="workorderQuantity">
      </el-table-column>
      <el-table-column label="填报数量" align="center" prop="recordQuantity">
      </el-table-column>
      <el-table-column label="标准工时(分)" align="center" prop="stdWorkTime">
      </el-table-column>
      <el-table-column label="正常工时(分)" align="center" prop="normalWorkinghours">
        <template slot-scope="scope">
          <span>{{ scope.row.normalWorkinghours || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="异常工时(分)" align="center" prop="abnormalWorkinghours">
        <template slot-scope="scope">
          <span>{{ scope.row.abnormalWorkinghours || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchCode">
        <template slot-scope="scope">
          <span>{{ scope.row.batchCode || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批号名称" align="center" prop="batchName">
        <template slot-scope="scope">
          <span>{{ scope.row.batchName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="录入原因" align="center" prop="inputReason">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_input_reason" :value="scope.row.inputReason" />
        </template>
      </el-table-column>
      <el-table-column label="填报人" align="center" prop="createBy">
        <template slot-scope="scope">
          <span>{{ scope.row.createBy || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="填报时间" align="center" width="100" prop="createTime">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime || "--" }}</span>
        </template>
      </el-table-column>

      <!-- 0未知 1汇报入库-普通生产 2汇报入库-返工生产 3汇报入库-样机生产 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['workinghours:record:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['workinghours:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改工时记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="display: flex; flex-wrap: wrap">
        <el-form-item label="工单编码" prop="workorderCode" class="form-item">
          <el-input v-model="form.workorderCode" placeholder="请输入工单编码" disabled />
        </el-form-item>
        <el-form-item label="产品编号" prop="productCode" class="form-item">
          <el-input v-model="form.productCode" placeholder="请输入产品编号" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName" class="form-item">
          <el-input v-model="form.productName" placeholder="请输入产品名称" disabled />
        </el-form-item>
        <el-form-item label="规格型号" prop="productSpc" class="form-item">
          <el-input v-model="form.productSpc" placeholder="请输入规格型号" disabled />
        </el-form-item>
        <el-form-item label="批次号" prop="batchCode" class="form-item">
          <el-input v-model="form.batchCode" placeholder="请输入批次号" disabled />
        </el-form-item>
        <el-form-item label="批号名称" prop="batchName" class="form-item">
          <el-input v-model="form.batchName" placeholder="请输入批号名称" disabled />
        </el-form-item>
        <el-form-item label="工单数量" prop="workorderQuantity" class="form-item">
          <el-input v-model="form.workorderQuantity" placeholder="请输入批号名称" disabled />
        </el-form-item>
        <div class="form-item"></div>
        <el-form-item label="SN码" prop="snCode" class="form-item">
          <el-input v-model="form.snCode" placeholder="请输入SN码" />
        </el-form-item>
        <el-form-item label="填报数量" prop="recordQuantity" class="form-item">
          <el-input v-model.number="form.recordQuantity" placeholder="请输入填报数量" />
        </el-form-item>
        <el-form-item label="产线名称" prop="lineName" class="form-item">
          <el-select v-model="form.lineName" placeholder="请选择产线名称" @change="(val) => lineChange(val, 'form')" style="width: 100%">
            <el-option v-for="item in lineList" :key="item.lineNo" :label="item.lineName" :value="item.lineName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产线ID" prop="lineId" class="form-item" v-show="false">
          <el-input v-model="form.lineId" placeholder="请输入产线ID" />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName" class="form-item">
          <el-select v-model="form.processName" placeholder="请选择工序名称" @change="(val) => processChange(val, 'form')" style="width: 100%">
            <el-option v-for="item in processList" :key="item.processId" :label="item.processName" :value="item.processName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工序ID" prop="processId" class="form-item" v-show="false">
          <el-input v-model="form.processId" placeholder="请输入工序ID" />
        </el-form-item>
        <el-form-item label="正常工时(分)" prop="normalWorkinghours" class="form-item">
          <el-input v-model="form.normalWorkinghours" placeholder="请输入正常工时" type="number" @input="validatePositiveInteger('normalWorkinghours')" @blur="validateBlur('normalWorkinghours')" />
        </el-form-item>

        <el-form-item label="异常工时(分)" prop="abnormalWorkinghours" class="form-item" style="flex: 0 0 50%">
          <el-input v-model="form.abnormalWorkinghours" placeholder="请输入异常工时" type="number" @input="validatePositiveInteger('abnormalWorkinghours')" @blur="validateBlur('abnormalWorkinghours')" />
        </el-form-item>

        <el-form-item label="录入原因" prop="inputReason" class="form-item">
          <el-select v-model="form.inputReason" placeholder="请选择录入原因" style="width: 100%">
            <el-option v-for="item in recordResonList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <div class="form-item"></div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
  getWorkInfo,
  getAllLineList,
  getAllProcessList,
} from "@/api/mes/workinghours/record";
export default {
  name: "Record",
  dicts: ["mes_order_type", "sys_input_reason"],
  data() {
    return {
      //录入原因：1来料异常，2设备异常，3，VCU加工，4，IGBT加工，5其他
      recordResonList: [
        {
          label: "来料异常",
          value: 1,
        },
        {
          label: "设备异常",
          value: 2,
        },
        {
          label: "其他",
          value: 3,
        },
      ],
      lineList: [],
      processList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工时记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      workorderId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderCode: null,
        productCode: null,
        productName: null,
        productSpc: null,
        snCode: null,
        lineId: null,
        lineName: null,
        processId: null,
        processName: null,
        normalWorkinghours: null,
        abnormalWorkinghours: null,
        batchCode: null,
        batchName: null,
        orderType: null,
      },
      // 表单参数
      form: {
        lineId: null,
        lineName: null,
        processId: null,
        processName: null,
        workorderQuantity: null,
        recordQuantity: null,
        inputReason: null,
      },
      // 表单校验
      rules: {
        workorderCode: [
          { required: true, message: "工序名称不能为空", trigger: "blur" },
        ],
        inputReason: [
          { required: true, message: "录入原因不能为空", trigger: "change" },
        ],

        // normalWorkinghours: [
        //   { required: true, message: "正常工时不能为空", trigger: "blur" }
        // ],
        // abnormalWorkinghours: [
        //   { required: true, message: "异常工时不能为空", trigger: "blur" }
        // ],
      },
    };
  },
  created() {
    this.getList();
    this.getAllLineList();
    this.getAllProcessList();
  },
  mounted() {
    console.log(111, this.dict.type);
    console.log(111, this.dict.type.mes_order_type.length);

    //  console.log(111,this.dict.type.mes_order_type)
    console.log(222, this.recordResonList);
    console.log(222, this.recordResonList.length);
  },
  methods: {
    // 仅允许输入正整数
    validatePositiveInteger(field) {
      this.form[field] = this.form[field].replace(/\D/g, ''); // 只保留数字
    },
    // 失焦时，确保输入有效
    validateBlur(field) {
      if (!this.form[field] || Number(this.form[field]) <= 0) {
        this.form[field] = '';
      }
    },
    lineChange(val, formName) {
      console.log(val, formName);
      console.log(this.lineList);
      console.log(this.lineList.find((item) => item.lineName === val));
      if (val) {
        //edit begin by zyj 2024/10/21 lineId  应该取 lineId 不是取  lineNo
        // this[formName].lineId = this.lineList.find(
        //   (item) => item.lineName === val
        // ).lineNo;
        this[formName].lineId = this.lineList.find(
          (item) => item.lineName === val
        ).lineId;
        //edit end by zyj 2024/10/21 lineId  应该取 lineId 不是取  lineNo
      } else {
        this[formName].lineId = val;
      }
    },
    processChange(val, formName) {
      if (val) {
        this[formName].processId = this.processList.find(
          (item) => item.processName === val
        ).processId;
      } else {
        this[formName].processId = "";
      }
    },
    getAllLineList() {
      getAllLineList().then((res) => {
        this.lineList = res.data;
      });
    },
    getAllProcessList() {
      getAllProcessList().then((res) => {
        this.processList = res.data;
      });
    },

    /** 查询工时记录列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then((response) => {
        this.recordList =
          response.rows && response.rows.length ? response.rows : [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workorderCode: null,
        productCode: null,
        productName: null,
        productSpc: null,
        snCode: null,
        lineId: null,
        lineName: null,
        processId: null,
        processName: null,
        normalWorkinghours: null,
        abnormalWorkinghours: null,
        createBy: null,
        createTime: null,
        batchCode: null,
        batchName: null,
        orderType: null,
        inputReason: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log(this.queryParams, "=====queryParams===");
      if (this.queryParams.time) {
        this.queryParams["createTimeBegin"] = this.queryParams.time[0];
        this.queryParams["createTimeEnd"] = this.queryParams.time[1];
      } else {
        this.queryParams["createTimeBegin"] = null;
        this.queryParams["createTimeEnd"] = null;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工时记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRecord(id).then((response) => {
        this.form = response.data;
        this.workorderId = response.data.workorderId;
        this.open = true;
        this.title = "修改工时记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!this.form.normalWorkinghours && !this.form.abnormalWorkinghours) {
          return this.$message.error("正常工时和异常工时不能全为空!");
        }
        if (valid) {
          this.form.workorderId = this.workorderId;
          if (this.form.id != null) {
            updateRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      let newIds = "";
      if (typeof ids != "object") {
        newIds = row.id;
      } else {
        newIds = ids.join(",");
      }
      this.$modal
        .confirm('是否确认删除工时记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRecord(newIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log(this.queryParams, "=====queryParams===");
      if (this.queryParams.time) {
        this.queryParams["createTimeBegin"] = this.queryParams.time[0];
        this.queryParams["createTimeEnd"] = this.queryParams.time[1];
      } else {
        this.queryParams["createTimeBegin"] = null;
        this.queryParams["createTimeEnd"] = null;
      }
      this.download(
        "/mes/workinghours/record/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.form-item {
  flex: 50%;
}
</style>
